# -*- coding: utf-8 -*-
"""
summary:
    此类是实现在Template里面方便使用 Filter 来调用sidebar，并自已获取信息，不用主Views传数据
    避免重视在Views里面反复的读信息传到Template里面
author:
    Jason Lee<huacnlee@gmail.com>
"""
from django.template import Library,defaultfilters
from settings import *
from apps.blog.models import Profile,Post
from utils import helper,logs
import traceback

register = Library()

__FILTER_NAME_PREFIX = "componsent_sidebar_"
__TEMPLATE_ROOT = "components/sidebar/"

def recent_blogs(size):
    """
    summary:
        返回最新博客列表
    """
    _template='%srecent-blogs.html' % (__TEMPLATE_ROOT)

    profiles = []
    try:
        profiles = Profile.objects.filter(user__status = 1).order_by('-user__id')[0:size]
    except:
        logs.write(traceback)

    data = {
            'profiles' : profiles,
            }

    return defaultfilters.safe(helper.view.out_html(_template,data))

def top_blogs(size):
    """
    summary:
        返回族人英雄榜
    """
    _template='%stop-blogs.html' % (__TEMPLATE_ROOT)

    profiles = []
    try:
        profiles = Profile.objects.filter(user__status = 1).order_by('-user__score')[0:size]
    except:
        logs.write(traceback)

    data = {
            'profiles' : profiles,
            }

    return defaultfilters.safe(helper.view.out_html(_template,data))

def recent_posts(size):
    """
    summary:
        最新文章
    """
    _template='%srecent-posts.html' % (__TEMPLATE_ROOT)

    posts = []
    try:
        posts = Post.objects.filter(status = 1).order_by("-id")[:size]
    except:
        logs.write(traceback)

    data = {
            'posts' : posts,
            }

    return defaultfilters.safe(helper.view.out_html(_template,data))

# regist filter
register.filter('%srecent_blogs' % __FILTER_NAME_PREFIX, recent_blogs)
register.filter('%stop_blogs' % __FILTER_NAME_PREFIX, top_blogs)
register.filter('%srecent_posts' % __FILTER_NAME_PREFIX, recent_posts)
